package zct.proj.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Typeface;
import android.os.Environment;
import android.util.Log;

public class FontUtil {

	private static Typeface simKai = null;
	
	private static Typeface getSimKai(Context context) {
		
//		if (simKai == null) {
//			File sddir = Environment.getExternalStorageDirectory();
//			try {
//				String ttf = sddir.getCanonicalPath() + "/simkai.ttf";
//				simKai = Typeface.createFromFile(ttf);
//			} catch (IOException e) {
//				e.printStackTrace();
//			}
//		}
		
		if (simKai == null) {
			AssetManager mgr = context.getResources().getAssets();
			try {
				InputStream stream = mgr.open(Const.RESPATH_SIMKAI, AssetManager.ACCESS_STREAMING);
				ZipInputStream zis = new ZipInputStream(stream);
				ZipEntry ze = zis.getNextEntry();
				if (ze != null) {
					String path = context.getFilesDir() + "/" + ze.getName();
					FileOutputStream fos = new FileOutputStream(path, false);
					byte[] bts = new byte[1024];
					int size = 0;
					while ((size = zis.read(bts, 0, bts.length)) > -1) {
						fos.write(bts, 0, size);
					}
					fos.close();
					zis.closeEntry();
					simKai = Typeface.createFromFile(path);
				}
				zis.close();
			} catch (IOException e) {
				simKai = Typeface.DEFAULT;
				Log.v("getSimKai", "Cannot open font file.");
				e.printStackTrace();
			}
		}
		return simKai;
	}
	
	public static Typeface getTypeface(Context context, String fontName) {
		if (Const.FONT_NAME_KAI.equals(fontName)) {
//			Log.v("getTypeface", "simkai:" + fontName);
			return getSimKai(context);
		} else if (Const.FONT_NAME_SERIF.equals(fontName)) {
//			Log.v("getTypeface", "serif:" + fontName);
			return Typeface.SERIF;
		} else {
//			Log.v("getTypeface", "default:" + fontName);
			return Typeface.SERIF;
		}
	}
}
